/**
 * Copyright 2016 JustWayward Team
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.songcha.module_bookreader.ui.view.readview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.drawable.GradientDrawable;
import android.view.View;

import com.songcha.library_common.util.LogUtil;
import com.songcha.module_bookreader.manager.SettingManager;
import com.songcha.module_bookreader.manager.ThemeManager;
import com.songcha.module_bookreader.utils.LogUtils;

import static java.lang.Math.abs;

/***
 * 平移翻页
 */
public class TranslateReadWidget extends BaseReadView {

    private Path mPath0;

    GradientDrawable mBackShadowDrawableLR;
    GradientDrawable mBackShadowDrawableRL;

    private Rect mSrcRect=new Rect(0,0,mCanvasWidth,mCanvasHeight);
    private Rect mDstRect=new Rect(0,0,mCanvasWidth,mCanvasHeight);
    private Rect mSrcNextRect=new Rect(0,0,mCanvasWidth,mCanvasHeight);
    private Rect mDstNextRect=new Rect(0,0,mCanvasWidth,mCanvasHeight);

    private FlipDirection mFlipDirection=FlipDirection.NONE;

    private float mDeltaX=0f;


    public TranslateReadWidget(Context context, int width, int height, String bookId,
                               IOnReadStateChangeListener listener, boolean isOnDrawWord, String fontPath,
                               boolean isFromSD,boolean isChapterLastAdvertPreLoadEnabled,
                               IOnChapterAdvertListener chapterAdvertListener) {
        super(context,width,height, bookId, listener,isOnDrawWord,fontPath,isFromSD,isChapterLastAdvertPreLoadEnabled,chapterAdvertListener);

        mTouch.x = 0.01f;
        mTouch.y = 0.01f;

        mPath0 = new Path();

        int[] mBackShadowColors = new int[]{0xaa666666, 0x666666};
        mBackShadowDrawableRL = new GradientDrawable(GradientDrawable.Orientation.RIGHT_LEFT, mBackShadowColors);
        mBackShadowDrawableRL.setGradientType(GradientDrawable.LINEAR_GRADIENT);

        mBackShadowDrawableLR = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, mBackShadowColors);
        mBackShadowDrawableLR.setGradientType(GradientDrawable.LINEAR_GRADIENT);
    }

    @Override
    protected void drawCurrentPageArea(Canvas canvas) {
        //if(abs(mTouchDelta)==0 || abs(mTouchDelta)==mCanvasWidth) return;

        mPath0.reset();
        canvas.save();

        //不能判断动画是否完成，否则没有拖动动画效果
        //pagebitmap会覆盖整个画布
        //if(!mScroller.isFinished()){
            //LogUtils.d("aaa","drawCurrentPageArea1,"+mTouchDeltaX);

        //canvas.drawBitmap(mCurPageBitmap,0,0,null);
            //float tmp=mTouchDeltaX;
        float touchDeltaX = mTouchDeltaX;
        if(mTouchDeltaX > mCanvasWidth)
            touchDeltaX = mCanvasWidth;
        if(mTouchDeltaX < -mCanvasWidth)
            touchDeltaX = -mCanvasWidth;

        if (isRight()) {
            //src裁剪区域，相对于bitmap；dst绘制区域，相对于canvas
            // if(mTouchDelta>0) mTouchDelta=0;
            if(touchDeltaX > 0){
                mSrcRect.left = 0;
                mSrcRect.right = mCanvasWidth;
                mDstRect.left = 0;
                mDstRect.right = mCanvasWidth;
            }else{
                mSrcRect.left = (int)-touchDeltaX;
                mSrcRect.right = mCanvasWidth;
                mDstRect.left = 0;
                mDstRect.right = mCanvasWidth + (int)touchDeltaX;
            }
            canvas.drawBitmap(mCurPageBitmap,mSrcRect,mDstRect,null);
        } else {
            if(touchDeltaX < 0){
                mSrcRect.left = 0;
                mSrcRect.right = mCanvasWidth;
                mDstRect.left = 0;
                mDstRect.right = mCanvasWidth;
            }else{
                mSrcRect.left = 0;
                mSrcRect.right = mCanvasWidth - (int)touchDeltaX;
                mDstRect.left = (int)touchDeltaX;
                mDstRect.right = mCanvasWidth;
            }
            canvas.drawBitmap(mCurPageBitmap,mSrcRect,mDstRect,null);
        }

        try {
            canvas.restore();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void drawCurrentPageShadow(Canvas canvas) {
     /*   canvas.save();
        GradientDrawable shadow;
        if (mLastX > mCanvasWidth >> 1) {
            shadow = mBackShadowDrawableLR;
            shadow.setBounds((int) (mCanvasWidth + mTouchDelta - 5), 0, (int) (mCanvasWidth + mTouchDelta + 5), mCanvasHeight);

        } else {
            shadow = mBackShadowDrawableRL;
            shadow.setBounds((int) (mTouchDelta - 5), 0, (int) (mTouchDelta + 5), mCanvasHeight);
        }
        shadow.draw(canvas);
        try {
            canvas.restore();
        } catch (Exception e) {

        }*/
    }

    @Override
    protected void drawCurrentBackArea(Canvas canvas) {
        // none
    }

    @Override
    protected void drawNextPageAreaAndShadow(Canvas canvas) {
        canvas.save();

        //if(abs(mTouchDelta)==0 || abs(mTouchDelta)==mCanvasWidth) return;
        //canvas.drawBitmap(mNextPageBitmap,0,0,null);

        //float tmp=mTouchDeltaX;
        //if(!mScroller.isFinished()){

        /*if(mIsStartFlipAnimation && !mScroller.isFinished()){
            LogUtils.d("aaa drawNextPageAreaAndShadow",mTouchDelta);
            canvas.restore();
            return;
        }*/
        float touchDeltaX = mTouchDeltaX;
        if(mTouchDeltaX > mCanvasWidth)
            touchDeltaX = mCanvasWidth;
        if(mTouchDeltaX < -mCanvasWidth)
            touchDeltaX = -mCanvasWidth;

        if (isRight()) {
            if(touchDeltaX > 0){
                mSrcNextRect.left = 0;
                mSrcNextRect.right = 0;
                mDstNextRect.left = mCanvasWidth;
                mDstNextRect.right = mCanvasWidth;
            }else{
                mSrcNextRect.left = 0;
                mSrcNextRect.right = (int) - touchDeltaX;
                mDstNextRect.left = mCanvasWidth + (int)touchDeltaX;
                mDstNextRect.right = mCanvasWidth;
            }
            canvas.drawBitmap(mNextPageBitmap,mSrcNextRect,mDstNextRect,null);
        } else {
            // if(mTouchDelta<0) mTouchDelta=0;
            if(touchDeltaX < 0){
                mSrcNextRect.left = mCanvasWidth;
                mSrcNextRect.right = mCanvasWidth;
                mDstNextRect.left = 0;
                mDstNextRect.right = 0;
            }else{
                mSrcNextRect.left = mCanvasWidth - (int)touchDeltaX;
                mSrcNextRect.right = mCanvasWidth;
                mDstNextRect.left = 0;
                mDstNextRect.right = (int)touchDeltaX;
            }
            canvas.drawBitmap(mNextPageBitmap,mSrcNextRect,mDstNextRect,null);
        }

        try {
            canvas.restore();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void calcPoints() {

    }

    @Override
    protected void calcCornerXY(float x, float y,FlipDirection direction) {

    }

    @Override
    public void computeScroll() {
        //computeScrollOffset返回true表示动画未完成，但更新不及时
        if (mScroller.computeScrollOffset()) {
            float x = mScroller.getCurrX();
            float y = mScroller.getCurrY();
            mDeltaX = x;
            if (isRight()) {
                mTouchDeltaX = -(mCanvasWidth - x);
            } else {
                mTouchDeltaX = x;
            }
            mTouch.y = y;
            //mTouchDelta = mTouch.x - mLastX;
            postInvalidate();
        }else{
            //mTouchDeltaX = 0;
        }
        super.computeScroll();
    }

    @Override
    protected void startAnimation(FlipDirection direction) {
        int dx;
        //if (mLastX > mCanvasWidth / 2)
        //if (direction==FlipDirection.RIGHT)
        //dx下一页为负，上一页为正，代表移出屏幕的偏移
        //startScroll第三个参数是offset而不是point

        mFlipDirection=direction;
        //LogUtils.d("aaa startAnimation",mFlipDirection);
        if (isRight()) {
            dx = (int) -(mCanvasWidth + mTouchDeltaX);
            mScroller.startScroll((int) (mCanvasWidth + mTouchDeltaX), (int) mTouch.y, dx, 0, START_ANIMATION_TIME);
        } else {
            dx = (int) (mCanvasWidth - mTouchDeltaX);
            mScroller.startScroll((int) mTouchDeltaX, (int) mTouch.y, dx, 0, START_ANIMATION_TIME);
        }

        //LogUtils.d("aaa",mTouchDelta);
    }

    private boolean isRight(){
        return mFlipDirection == FlipDirection.RIGHT;
    }

    @Override
    protected void onAnimationUpdate(FlipDirection direction) {
        mFlipDirection=direction;
    }

    @Override
    protected void abortAnimation() {
        if (!mScroller.isFinished()) {
            mScroller.abortAnimation();
        }
    }

    @Override
    protected void restoreAnimation(FlipDirection direction) {
        int startX;
        int dx;
        mFlipDirection = direction;
        if (isRight()) {
            startX = (int)(mCanvasWidth + mTouchDeltaX);
            dx = (int)-mTouchDeltaX;
        } else {
            startX = (int)mTouchDeltaX;
            dx = (int)-mTouchDeltaX;
        }
        mScroller.startScroll(startX, (int)mTouch.y, dx, 0, CANCEL_ANIMATION_TIME);
    }

    public void setBitmaps(Bitmap bm1, Bitmap bm2) {
        mCurPageBitmap = bm1;
        mNextPageBitmap = bm2;
    }

    @Override
    protected void drawChapterLastAdvertViewAnimation(Canvas canvas,View adView) {
        startChapterLastAdvertViewAnim(adView,mTouchDeltaX);
    }

    private void startChapterLastAdvertViewAnim(View adView,float deltaX){
        //if(deltaX == 0f) return;
        LayoutParams lp = (LayoutParams) adView.getLayoutParams();
        lp.leftMargin = (int)(deltaX);
        lp.rightMargin = (int)(-deltaX);
        adView.setLayoutParams(lp);
    }

    @Override
    public synchronized void setTheme(int theme) {
        resetTouchPoint();
        Bitmap bg = ThemeManager.getThemeDrawable(theme);
        super.setBackgroundBitmap(bg);
    }

    @Override
    public void setBackgroundBitmap(Bitmap bitmap) {
        resetTouchPoint();
        super.setBackgroundBitmap(bitmap);
    }
}
